import logging
from datetime import datetime, timedelta

from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger

from app.db.clickhouse_db import get_clickhouse_pool, ClickHouseHTTPPool


def my_daily_task():
    logging.info("开始执行删除两客一危定时")
    clickHouseHttPPool: ClickHouseHTTPPool = get_clickhouse_pool()
    simple_date_format = "%Y-%m-%d %H:%M:%S"
    now = datetime.now()
    to_day_hours_ago = (now - timedelta(hours=48)).strftime(simple_date_format)
    clickHouseHttPPool.execute(f"ALTER TABLE lkywgps0 DELETE WHERE rksj< '{to_day_hours_ago}'")
    logging.info("结束执行删除两客一危定时")

def my_daily_task1():
    logging.info("开始执行删除卡口过车定时")
    clickHouseHttPPool: ClickHouseHTTPPool = get_clickhouse_pool()
    simple_date_format = "%Y-%m-%d %H:%M:%S"
    now = datetime.now()
    to_day_hours_ago = (now - timedelta(hours=48)).strftime(simple_date_format)
    clickHouseHttPPool.execute(f"ALTER TABLE kkgcxx DELETE WHERE rksj< '{to_day_hours_ago}'")
    logging.info("结束执行删除卡口过车定时")

def start_scheduler():
    scheduler = AsyncIOScheduler()

    # 每天凌晨1点整执行（时区可配置）
    scheduler.add_job(
        my_daily_task,
        trigger=CronTrigger(hour=1, minute=0, second=30),  # 1:00:00
        timezone="Asia/Shanghai"  # 设置为你的时区
    )

    scheduler.add_job(
        my_daily_task1,
        trigger=CronTrigger(hour=2, minute=0, second=30),  # 1:00:00
        timezone="Asia/Shanghai"  # 设置为你的时区
    )

    scheduler.start()